<template>
  <view class="page-container">
    <!-- 页面头部 -->
    <view class="header">
      <view class="header-left" @click="goBack">
        <u-icon name="arrow-left" color="#fff" size="20"></u-icon>
      </view>
      <view class="header-title">选择人员</view>
      <view class="header-right" @click="confirmSelection">
        <text class="confirm-text">确定</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view class="content-area" :scroll-y="true" :style="{ height: scrollHeight }">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <u-loading-icon mode="spinner" color="#667eea" size="40"></u-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 角色分组列表 -->
      <view v-else-if="roleGroups.length > 0" class="role-groups">
        <view 
          v-for="roleGroup in roleGroups" 
          :key="roleGroup.roleId"
          class="role-group"
        >
          <!-- 角色头部 -->
          <view class="role-header" @click="toggleRoleGroup(roleGroup.roleId)">
            <view class="role-info">
              <text class="role-name">{{ roleGroup.roleName }}</text>
              <text class="user-count">({{ roleGroup.userCount }}人)</text>
            </view>
            <view class="role-actions">
              <u-checkbox 
                v-model="roleGroup.selected" 
                @change="handleRoleSelect(roleGroup)"
                :disabled="roleGroup.users.length === 0"
              ></u-checkbox>
              <u-icon 
                :name="roleGroup.expanded ? 'arrow-up' : 'arrow-down'" 
                color="#999" 
                size="16"
              ></u-icon>
            </view>
          </view>

          <!-- 用户列表 -->
          <view v-if="roleGroup.expanded" class="user-list">
            <view 
              v-for="user in roleGroup.users" 
              :key="user.id"
              class="user-item"
              @click="toggleUserSelect(user)"
            >
              <view class="user-info">
                <image 
                  v-if="user.avatar" 
                  :src="user.avatar" 
                  class="user-avatar"
                  mode="aspectFill"
                ></image>
                <view v-else class="user-avatar-placeholder">
                  <u-icon name="account" color="#999" size="20"></u-icon>
                </view>
                <view class="user-details">
                  <text class="user-name">{{ user.displayName }}</text>
                  <text class="user-phone" v-if="user.phone">{{ user.phone }}</text>
                </view>
              </view>
              <u-checkbox 
                v-model="user.selected" 
                @change="handleUserSelect(user, roleGroup)"
              ></u-checkbox>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else class="empty-container">
        <u-icon name="account-multiple" color="#ccc" size="60"></u-icon>
        <text class="empty-text">暂无人员数据</text>
      </view>
    </scroll-view>

    <!-- 底部统计 -->
    <view class="bottom-stats">
      <text class="stats-text">已选择 {{ selectedCount }} 人</text>
    </view>
  </view>
</template>

<script setup>
/**
 * 按角色分组的用户选择页面
 * @author Wu.Liang
 * @date 2025-01-30
 * @version 1.0.0
 */

import { ref, reactive, computed, onMounted } from 'vue'
import { staffApi } from '@/api/staff'

// 页面高度计算
const scrollHeight = ref('calc(100vh - 120px)')

// 响应式数据
const loading = ref(false)
const roleGroups = ref([])

// 计算属性
const selectedCount = computed(() => {
  let count = 0
  roleGroups.value.forEach(roleGroup => {
    roleGroup.users.forEach(user => {
      if (user.selected) {
        count++
      }
    })
  })
  return count
})

// 方法
const goBack = () => {
  uni.navigateBack()
}

const confirmSelection = () => {
  const selectedUsers = []
  roleGroups.value.forEach(roleGroup => {
    roleGroup.users.forEach(user => {
      if (user.selected) {
        selectedUsers.push({
          id: user.id,
          username: user.username,
          realName: user.realName,
          nickname: user.nickname,
          displayName: user.displayName,
          phone: user.phone,
          email: user.email,
          avatar: user.avatar
        })
      }
    })
  })
  
  // 通过事件总线传递选中的用户
  uni.$emit('staffSelected', selectedUsers)
  
  uni.navigateBack()
}

const toggleRoleGroup = (roleId) => {
  const roleGroup = roleGroups.value.find(rg => rg.roleId === roleId)
  if (roleGroup) {
    roleGroup.expanded = !roleGroup.expanded
  }
}

const handleRoleSelect = (roleGroup) => {
  // 角色全选/取消全选
  const isSelected = roleGroup.selected
  roleGroup.users.forEach(user => {
    user.selected = isSelected
  })
}

const toggleUserSelect = (user) => {
  user.selected = !user.selected
  // 更新角色选择状态
  updateRoleSelectionStatus(user.roleGroupId)
}

const handleUserSelect = (user, roleGroup) => {
  // 更新角色选择状态
  updateRoleSelectionStatus(roleGroup.roleId)
}

const updateRoleSelectionStatus = (roleId) => {
  const roleGroup = roleGroups.value.find(rg => rg.roleId === roleId)
  if (roleGroup) {
    const selectedUsers = roleGroup.users.filter(user => user.selected)
    roleGroup.selected = selectedUsers.length === roleGroup.users.length && roleGroup.users.length > 0
  }
}

const loadRoleGroups = async () => {
  if (loading.value) {
    return
  }
  
  loading.value = true
  
  try {
    // 从页面参数获取物业公司ID
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const propertyCompanyId = currentPage.options?.propertyCompanyId
    
    if (!propertyCompanyId) {
      uni.showToast({
        title: '缺少物业公司ID参数',
        icon: 'none'
      })
      return
    }
    
    // 调用API获取按角色分组的用户列表
    const response = await staffApi.getUsersByRoleGroup(propertyCompanyId)
    
    if (response && response.code === 200) {
      const data = response.data || []
      
      // 处理数据，添加选择状态和展开状态
      roleGroups.value = data.map(roleGroup => ({
        ...roleGroup,
        selected: false,
        expanded: false,
        users: roleGroup.users.map(user => ({
          ...user,
          selected: false,
          roleGroupId: roleGroup.roleId
        }))
      }))
      
      console.log('加载按角色分组的用户列表成功：', roleGroups.value)
    } else {
      const errorMessage = response?.message || response?.msg || '加载用户列表失败'
      throw new Error(errorMessage)
    }
  } catch (error) {
    console.error('加载按角色分组的用户列表失败:', error)
    uni.showToast({
      title: error.message || '加载用户列表失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadRoleGroups()
})
</script>

<style scoped>
/* 页面容器规范 */
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 头部样式 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 30rpx;
  background-color: #667eea;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-left,
.header-right {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #fff;
}

.confirm-text {
  font-size: 28rpx;
  color: #fff;
}

/* 内容区域 */
.content-area {
  margin-top: 88rpx;
  padding: 20rpx;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
  margin-top: 20rpx;
}

/* 角色分组列表 */
.role-groups {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.role-group {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.role-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  background-color: #f8f9fa;
  border-bottom: 1rpx solid #eee;
}

.role-info {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.role-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.user-count {
  font-size: 24rpx;
  color: #666;
}

.role-actions {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

/* 用户列表 */
.user-list {
  background-color: #fff;
}

.user-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.user-item:last-child {
  border-bottom: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
  flex: 1;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #f0f0f0;
}

.user-avatar-placeholder {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.user-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.user-phone {
  font-size: 24rpx;
  color: #666;
}

/* 空状态 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-top: 20rpx;
}

/* 底部统计 */
.bottom-stats {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.stats-text {
  font-size: 28rpx;
  color: #667eea;
  font-weight: 500;
}
</style>
